package models.monitor;

import java.util.*;

import play.Logger;
import play.db.ebean.*;
import play.data.validation.Constraints.*;
import play.data.format.*;
import play.mvc.Http.Context;
import play.mvc.Http.Request;
import service.Paging;

import javax.persistence.*;

import com.avaje.ebean.Ebean;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.ExpressionList;
import com.avaje.ebean.Page;
import com.avaje.ebean.PagingList;
import com.avaje.ebean.Query;
import com.fasterxml.jackson.annotation.JsonFormat;

@Entity
public class ScheduleETL extends Model{
	@Id
	public Integer scheduleKey;
	  
	public Integer timeKey;
	
	@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy/MM/dd hh")
	public Date time;
	
	public Integer appId;
	
	public String appName;
	
	public Integer mode;
	
	public Integer type;
	
	public Integer priority;
	
	public String actionName;
	
	@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy/MM/dd hh:mm:ss")
	public Date startTime;
	
	@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy/MM/dd hh:mm:ss")
	public Date endTime;
	
	public Integer status;
	
	public String description;
	
	public int run_time;
	
	public static Finder<Long,ScheduleETL> find = new Finder(
		Long.class, ScheduleETL.class
	);
	
	public static Paging search(int game, int type, int status, Date startTime, Date endTime){		
		Request request = Context.current().request();
		
		List<ScheduleETL> list = null;
		Paging paging = null;
		
		int pageSize = Integer.parseInt(request.getQueryString("pageSize") == null ? "0" : request.getQueryString("pageSize"));
    	int page = Integer.parseInt(request.getQueryString("page") == null ? "0" : request.getQueryString("page"));
    	
    	//EbeanServer desperado = Ebean.getServer("desperado");
    	
    	Query<ScheduleETL> query = Ebean.find(ScheduleETL.class);
    	
    	ExpressionList<ScheduleETL> expression = query.where();
    	
    	if(game > -1) expression.eq("app_id", game);
    	
    	if(type > 0) expression.eq("type", type);
    	
    	if(status > -1) expression.eq("status", status);
    	
    	if(startTime != null) expression.gt("start_time", startTime);
    	
    	if(endTime != null) expression.lt("end_time", endTime);
    	
    	if(pageSize > 0)
    	{
	    	PagingList<ScheduleETL> pagingList = expression.findPagingList(pageSize);
	    	
	    	Page<ScheduleETL> page0 = pagingList.setFetchAhead(false).getPage(page - 1);
	        list = page0.getList();
	        paging = new Paging(pagingList.getTotalRowCount(), list);
    	}
    	else
    	{
    		list = query.findList();
    		paging = new Paging(0, list);
    	}
    	
        return paging;
	}
}
